package com.cloud.pdd.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cloud.pdd.common.core.domain.AjaxResult;
import com.cloud.pdd.common.core.domain.TableDataInfo;
import com.cloud.pdd.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

public class BaseController {
    @Autowired
    Config config;


    public ModelAndView baseView(String title, String viewPath) {
        ModelAndView view = new ModelAndView(viewPath);
        view.addObject("title", title);
        view.addObject("webSite", config.getWebSite());
        view.addObject("staticVersion", config.getStaticVersion());
        view.addObject("defaultPageSize", config.getDefaultPageSize());
        view.addObject("staticSite", config.getStaticSite());
        view.addObject("imgUrl", config.getImgUrl());
        return view;
    }

    public ModelAndView baseViewAjax(String title, String viewPath) {
        ModelAndView view = new ModelAndView(viewPath);
        view.addObject("webSite", config.getWebSite());
        view.addObject("staticVersion", config.getStaticVersion());
        view.addObject("staticSite", config.getStaticSite());
        view.addObject("imgUrl", config.getImgUrl());
        return view;
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(IPage pageData) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(1);
        rspData.setRows(pageData.getRecords());
        rspData.setTotal(pageData.getTotal());
        return rspData;
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? success() : error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean result) {
        return result ? success() : error();
    }

    /**
     * 返回成功
     */
    public AjaxResult success() {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error() {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message) {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message) {
        return AjaxResult.error(message);
    }

    /**
     * 返回错误码消息
     */
    public AjaxResult error(AjaxResult.Type type, String message) {
        return new AjaxResult(type, message);
    }

}
